package com.iflyun.rabbitmq.utils;

import java.security.Security;
import java.util.Date;
import java.util.Properties;


import javax.mail.Authenticator;

import javax.mail.Message;
import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iflyun.rabbitmq.common.Common;


public class MailUtils {
	
	private final static Logger logger = LoggerFactory.getLogger(MailUtils.class);

	@SuppressWarnings("restriction")
	public static void Send(String message,String address) {

		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		//final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		// Get a Properties object
		Properties props = System.getProperties();
		props.setProperty("mail.smtp.host", "smtp.163.com");
		//props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
		//props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.port", "25");
		// props.setProperty("mail.smtp.socketFactory.port", "25");
		//props.setProperty("mail.smtp.socketFactory.port", "587");
		props.put("mail.smtp.auth", "true");
		final String username = Common.SEND_UNAME;
		final String password = Common.SEND_PWD;
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		// -- Create a new message --
		session.setDebug(true);
		Message msg = new MimeMessage(session);

		// -- Set the FROM and TO fields --
		try {
			msg.setFrom(new InternetAddress(username + "@163.com"));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));
			msg.setSubject("RabbitMQ监测");
			msg.setText(message);
			msg.setSentDate(new Date());
			Transport transport = session.getTransport("smtp");
			// smtp验证，就是你用来发邮件的邮箱用户名密码
			transport.connect(Common.VALUE_SMTP, Common.SEND_UNAME, Common.SEND_PWD);
			// 发送
			Transport.send(msg);
			transport.close();
		} catch (AddressException e) {
			logger.error("地址有误",e);
		} catch (MessagingException e) {
			logger.error("发送有误",e);
		}

		logger.info("发送成功");
		
		
		
	}
	
	

}
